<template>
  <Container>
    <template v-slot:content>
      <TapList :tapList="energyList" :tapProps="{
        label: 'energyName',
        name: 'energyId'
      }" @handleClickTabs="handleClickTabs">

        <div class="energyConsumption">
          <div class="searchForm">
            <div class="label">选择时间：</div>
            <div class="formItem">
              <el-date-picker v-model="dataTimeList" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                clearable type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </div>
          <div v-loading="searchLoading" class="serachList" id="searchListRef"
            :style="{ height: `${(serachList.length > 3 ? 3 : serachList.length) * 46}px` }">
            <div class="searchItem" v-for="row, index in serachList" :key="index">
              <div class="label">选择区域：</div>
              <div class="formItem">
                <el-select v-model="row.areaId" filterable placeholder="请选择区域" @change="handleArea($event, index)">
                  <el-option v-for="item in areaList" :key="item.areaId" :label="item.areaName" :value="item.areaId">
                  </el-option>
                </el-select>
              </div>
              <div class="label">设备名称：</div>
              <div class="formItem">
                <el-select v-model="row.equipmentId" filterable clearable placeholder="请选择设备">
                  <el-option :disabled="equipmentIdList.includes(item.equipmentId) || energyId !== item.energyId"
                    v-for="item in row.equipmentList" :key="item.equipmentId" :label="item.equipmentName"
                    :value="item.equipmentId" />
                </el-select>
              </div>
              <div class="add btn" v-show="serachList.length == index + 1" @click="addSearchItem"><img
                  src="@/assets/icon/add.png" alt=""></div>
              <div class="del btn" v-show="serachList.length > 1" @click="delSearchItem(index)"><img
                  src="@/assets/icon/del.png" alt=""></div>
            </div>
          </div>
          <div v-loading="loading" class="echarts" :style="{ height: `calc(100% - ${serachList.length * 46 + 58}px)` }">
            <LineChart :legendList="legendList" :xAxisList="xAxisList" :seriesList="seriesList"></LineChart>
          </div>
        </div>
      </TapList>
    </template>
  </Container>
</template>

<script>

import Container from "@/components/Container"
import TapList from "@/components/TapList"
import energyApi from '@/api/energy'
import areaApi from '@/api/area'
import equipmentApi from '@/api/equipment'
import LineChart from "@/components/Echart/multiLine.vue"
import { getRecentTimeRange } from "@/utils/filterTime"
import dataQueryApi from "@/api/dataQuery"

export default {
  name: 'EnergyConsumptionComparison',
  components: {
    Container,
    TapList,
    LineChart
  },
  data() {
    return {
      loading: false,
      searchLoading: false,
      energyId: '',
      energyList: [],
      equipmentList: [],
      dataTimeList: [],
      serachList: [
        {
          areaId: '',
          equipmentId: '',
          energyId: '',
          equipmentList: []
        }
      ],
      legendList: [],
      xAxisList: [],
      seriesList: [],
      energyContrastList: []
    }
  },
  watch: {
    serachList: {
      handler(v) {
        let filterList = v.filter(e => {
          return e.equipmentId
        })
        this.equipmentIdList = filterList.map(e => e.equipmentId);
        this.energyContrast();
      },
      deep: true
    },
    dataTimeList: {
      handler(v) {
        this.energyContrast();
      },
      deep: true
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      let { data: energyList } = await energyApi.queryByCondition({});
      let { data: areaList } = await areaApi.queryByCondition({});
      let { data: equipmentList } = await equipmentApi.queryByCondition({});
      this.energyList = energyList || [];
      this.energyId = this.energyList[0]?.energyId;
      this.areaList = areaList || [];
      this.equipmentList = equipmentList || [];
      this.dataTimeList = getRecentTimeRange('week')
      console.log(getRecentTimeRange('week'))
    },
    async handleArea(e, index) {
      let row = this.serachList[index];
      this.searchLoading = true;
      let { data: equipmentList } = await equipmentApi.queryByCondition({ areaId: e });
      this.searchLoading = false;
      this.$set(this.serachList, index, {
        ...row,
        equipmentList
      })
    },
    addSearchItem() {
      this.serachList.push({
        areaId: '',
        equipmentId: '',
        energyId: ''
      })
      this.$nextTick(() => {
        let searchListRef = document.getElementById('searchListRef')
        searchListRef.scrollTo({
          top: searchListRef.scrollHeight, // 滚动到scrollHeight的位置，即底部
          behavior: 'smooth' // 实现平滑滚动，现代浏览器支持
        })
      })
    },
    delSearchItem(index) {
      this.serachList.splice(index, 1);
    },
    energyContrast() {
      if (this.dataTimeList &&
        this.equipmentIdList &&
        this.dataTimeList &&
        this.equipmentIdList.length &&
        this.dataTimeList.length) {
        let data = {
          equipmentIdList: this.equipmentIdList,
          startDate: this.dataTimeList[0],
          endDate: this.dataTimeList[1]
        }
        this.loading = true;
        dataQueryApi.energyContrast(data).then(res => {
          this.loading = false;
          let dataList = res.data || [];
          if (dataList.length) {
            this.legendList = dataList.map(e => e.equipmentName);
            this.xAxisList = dataList[0].dayData.map(e => e.recordTime);
            this.seriesList = dataList.map(e => {
              return {
                name: e.equipmentName,
                type: 'line',
                data: e.dayData.map(e => e.consumption)
              }
            });
          } else {
            this.legendList = this.xAxisList = this.seriesList = []
          }
        }).catch(err => {
          this.loading = false;
        })
      } else {
        this.legendList = this.xAxisList = this.seriesList = []
      }
    },
    handleClickTabs(e) {
      if (e && e.energyId) {
        this.energyId = e.energyId;
        this.dataTimeList = getRecentTimeRange('week');
        this.$set(this, 'serachList', [{
          areaId: '',
          equipmentId: '',
          energyId: ''
        }])
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.energyConsumption {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  padding: 20px;

  .searchForm {
    width: 100%;
    min-height: 46px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
  }

  .serachList {
    width: 100%;
    max-height: 138px;
    overflow: auto;

    .searchItem {
      width: 100%;
      height: 46px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;
      transition: all 0.2s;

      &:hover {
        background-color: #cecece4b;
      }

      .label {
        text-align: left;
      }

      .formItem {
        margin-right: 23px;
      }

      .btn {
        width: 30px;
        height: 30px;
        margin-right: 10px;
        cursor: pointer;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .echarts {
    width: 100%;
    min-height: calc(100% - 196px);
    background: #F8F8F8;
    border-radius: 5px;
    margin-top: 12px
  }
}
</style>
